﻿module Runner {

    export class OffenseDefense extends Phaser.Sprite {
        atkPower: number;
        dodgeChance: number;
        hitPoints: number;
        maxHitPoints: number;
        _lastHitPoints: number = 0;

        healthBar: Phaser.Graphics;
    }

    export function removeHitPoints<T extends OffenseDefense>(body: T, remove: number) { //return true if hurt
        body.hitPoints -= remove;
        updateHitPointBar(body);

        if (body.hitPoints <= 0) {

            body.animations.play('hurt');

            body.events.onAnimationComplete.add(function () {
                var tween = body.game.add.tween(body);
                tween.to({ alpha: 0 }, 500, Phaser.Easing.Linear.None);
                tween.onComplete.add(function () {
                    body.alive = false;
                    body.kill();
                });
                tween.start();
            }, this);
        }
    }

    export function dodge(dodgeChance: number): boolean {
        return Math.floor((Math.random() * 100) + 1) <= dodgeChance;
    }

    export function attackStrength(atkPower: number): number {
        return Math.floor((Math.random() * atkPower) + 1);
    }

    export function attack(bodyA: OffenseDefense, bodyB: OffenseDefense, battleWindow: Battle) {
        var heroAtk = (bodyA.key == battleWindow.heroSprite.key);
        var atkPower = attackStrength(bodyA.atkPower);
        if (atkPower > bodyB.hitPoints)
            atkPower = bodyB.hitPoints; //No overkill

        if (dodge(bodyB.dodgeChance)) {
            battleWindow.combatLog.writeWindowText(bodyB.name + ' dodged the attack');
        } else {
            removeHitPoints(bodyB, atkPower);

            bodyB.animations.stop();
            if (bodyB.hitPoints <= 0) {
                
                var hurt = bodyB.animations.play('hurt');
                hurt.onComplete.add(function (e) {
                    bodyB.kill();
                }, this);
                battleWindow.combatLog.writeWindowText(bodyB.name + ' was defeated!');
            } else {

                var animation = (heroAtk) ? bodyA.animations.play('slash_forward') : bodyA.animations.play('slash_backward');
                window.setTimeout(function (e) {
                    battleWindow.combatLog.writeWindowText(bodyB.name + ' hit for: ' + atkPower);
                }, 1000);
            }
        }
    }
}